<?php

namespace app\admin\controller\wdsxh\mall;
use app\admin\model\wdsxh\mall\Express;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 * 发货
 *
 * @icon fa fa-circle-o
 */

class Logistics extends Backend
{
    /**
     * Order模型对象
     * @var  \app\admin\model\wdsxh\mall\Logistics
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wdsxh\mall\Logistics;
        if ($this->auth->getGroups()[0]['group_id'] == 1) {
            $expressObj = (new Express())->where('store_id','-1')->select();
        }else{
            $expressObj = (new Express())->where('admin_id',$this->auth->id)->select();
        }
        $this->view->assign('expressObj',$expressObj);
    }

    public function import()
    {
        parent::import();
    }
    //发货
    public function logistics($ids = null)
    {
        if ($this->request->isPost()) {
            $orderObj = (new \app\admin\model\wdsxh\mall\Order())->get($ids);
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $params['order_id'] = $orderObj['id'];
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);
                    (new \app\api\model\wdsxh\mall\Order())->allowField(true)
                        ->where('id',$orderObj['id'])
                        ->update([
                            'status' => 2,
                        ]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }




}
